
export class CellPosition {
  constructor(
    public readonly col: string,
    public readonly row: number,
    public readonly original: string
  ) {
    this.col = col;
    this.row = row;
    this.original = original;
  }
}

export class CellArea {
  constructor(
    public readonly startCol: string,
    public readonly endCol: string,
    public readonly startRow: number,
    public readonly endRow: number,
    public readonly original: string
  ) {
    this.startCol = startCol;
    this.endCol = endCol;
    this.startRow = startRow;
    this.endRow = endRow;
    this.original = original;

  }
}

export class CellLine {
  constructor(
    public readonly startCol: string,
    public readonly endCol: string,
    public readonly row: number,
    public readonly original: string
  ) {
    this.startCol = startCol;
    this.endCol = endCol;
    this.row = row;
    this.original = original;
  }
}

export class CellColumn {
  constructor(
    public readonly col: string,
    public readonly startRow: number,
    public readonly endRow: number,
    public readonly original: string
  ) {
    this.col = col;
    this.startRow = startRow;
    this.endRow = endRow;
    this.original = original;
  }
}

interface ColumnRange {
  startCol: string;
  endCol: string;
  rowRanges: string[];
}

export type CellAreaOrPos = CellArea | CellLine | CellColumn | CellPosition;

export function combineCellRanges(cells: string[]): CellAreaOrPos[] {
  // 1. 解析所有单元格为行列数字
  const parsedCells: CellPosition[] = cells.map(cell => {
    const match = cell.match(/^([A-Z]+)(\d+)$/i);
    if (!match) {
      throw new Error(`Invalid cell format: ${cell}`);
    }

    const [, col, row] = match;
    return {
      col: col.toUpperCase(),
      row: parseInt(row),
      original: cell
    };
  });

  // 2. 按列分组，然后按行排序
  const colGroups: Record<string, number[]> = {};
  parsedCells.forEach(cell => {
    if (!colGroups[cell.col]) {
      colGroups[cell.col] = [];
    }
    colGroups[cell.col].push(cell.row);
  });

  // 3. 合并连续的行
  const mergedCols: Record<string, string[]> = {};
  Object.keys(colGroups)
    .sort((a, b) => a.localeCompare(b))
    .forEach(col => {
      const rows = [...new Set(colGroups[col])].sort((a, b) => a - b);
      let start = rows[0];
      const ranges: string[] = [];

      for (let i = 1; i <= rows.length; i++) {
        if (i < rows.length && rows[i] === rows[i - 1] + 1) {
          continue; // 继续寻找连续行
        } else {
          const end = rows[i - 1];
          ranges.push(start === end ? `${start}` : `${start}:${end}`);
          start = rows[i];
        }
      }

      mergedCols[col] = ranges;
    });

  // 4. 尝试合并相邻的列
  const finalRanges: CellAreaOrPos[][] = [];
  const cols = Object.keys(mergedCols).sort((a, b) => a.localeCompare(b));
  let currentColRange: ColumnRange | null = null;

  for (let i = 0; i < cols.length; i++) {
    const col = cols[i];
    const ranges = mergedCols[col];

    if (!currentColRange) {
      currentColRange = { startCol: col, endCol: col, rowRanges: ranges };
    } else if (
      col.charCodeAt(0) === currentColRange.endCol.charCodeAt(0) + 1 &&
      JSON.stringify(mergedCols[col]) === JSON.stringify(mergedCols[currentColRange.endCol])
    ) {
      // 列相邻且行范围相同
      currentColRange.endCol = col;
    } else {
      // 结束当前列范围
      finalRanges.push(formatColumnRange(currentColRange));
      currentColRange = { startCol: col, endCol: col, rowRanges: ranges };
    }
  }

  // 添加最后一个范围
  if (currentColRange) {
    finalRanges.push(formatColumnRange(currentColRange));
  }

  // 5. 扁平化结果并去重
  return [...new Set(finalRanges.flat())];
}

// 辅助函数：格式化列范围
function formatColumnRange(colRange: ColumnRange): CellAreaOrPos[] {
  // if (colRange.startCol === colRange.endCol) {
  //   return colRange.rowRanges.map(r => `${colRange.startCol}${r}`);
  // }

  return colRange.rowRanges.map(r => {
    const [startRow, endRow] = r.includes(':')
      ? r.split(':').map(s => parseInt(s))
      : [r, r].map(s => parseInt(s));

    const startCol = colRange.startCol;
    const endCol = colRange.endCol;
    let original;
    if (startRow === endRow && startCol === endCol) {
      original = `${colRange.startCol}${startRow}`;
      return new CellPosition(startCol,startRow,original);
    } else {
      original = `${colRange.startCol}${startRow}:${colRange.endCol}${endRow}`;
      if (startRow === endRow) {
        return new CellLine(startCol, endCol, startRow, original);
      }
      if (startCol === endCol) {
        return new CellColumn(startCol, startRow, endRow, original);
      }
      return { startCol, endCol, startRow, endRow, original };
    }
  });
}

function test() {
  // 使用示例
  const cells = ['A1', 'A2', 'B1', 'B2', 'C3', 'D4', 'D5', 'E4', 'E5'];
  const result = combineCellRanges(cells);
  console.log(result); // 输出: ["A1:B2", "C3", "D4:E5"]
}